/** @jsxImportSource @emotion/react */
import { useEffect } from "react";
import { publicRuntimeConfig } from "../next.config";
import Router, { withRouter } from "next/router";
import { connect } from "react-redux";
import Link from "next/link";
import LRU from "lru-cache";

import { request } from "../lib/api";

import { Button, Tabs } from "antd";
import styled from "@emotion/styled";
import { MailOutlined } from "@ant-design/icons";

import Repo from "../components/Repo";

// 使用LRU缓存数据
const cache = new LRU({
  // 缓存时效为10分钟，
  maxAge: 1000 * 60 * 10,
});

// 缓存数据
// let cachedUserRepos, cachedUserStaredRepos;

let isServer = typeof window === "undefined";
function Index({ userRepos, userStaredRepos, user, router }) {
  // useEffect(() => {
  //   axios.get("/api/user/info").then((res) => console.log(res));
  // }, []);

  const tabKey = router.query.key || "1";

  const handleTabChange = (activeKey) => {
    Router.push(`/?key=${activeKey}`);
  };

  useEffect(() => {
    if (!isServer) {
      // cachedUserRepos = userRepos;
      // cachedUserStaredRepos = userStaredRepos;
      if (userRepos) {
        cache.set("userRepos", userRepos);
      }
      if (userStaredRepos) {
        cache.set("userStaredRepos", userStaredRepos);
      }
    }
  }, [userRepos, userStaredRepos]);

  if (!user || !user.id) {
    return (
      <LoginDiv>
        <p>您还没有登录</p>
        <Button type="primary" href={publicRuntimeConfig.OAUTH_URL}>
          点击去登陆
        </Button>
      </LoginDiv>
    );
  }

  return (
    <UserRoot>
      <UserInfo>
        <img
          src={user.avatar_url}
          alt="user avatar"
          className="avatar"
          css={{ width: "100%", borderRadius: "5px" }}
        />
        <Login>{user.login}</Login>
        <Name>{user.name}</Name>
        <Bio>{user.bio}</Bio>
        <p className="email">
          <MailOutlined style={{ marginRight: 10 }} />
          <a href={`mailto:1611885458@qq.com`}>1611885458@qq.com</a>
        </p>
      </UserInfo>
      <UserRepos>
        <Tabs activeKey={tabKey} onChange={handleTabChange} animated={false}>
          {/* <Tabs defaultActiveKey="1" animated={false}> */}
          <Tabs.TabPane tab="你的仓库" key="1">
            {userRepos.map((item) => (
              <Repo repo={item} key={item.id} />
            ))}
          </Tabs.TabPane>
          <Tabs.TabPane tab="你关注的仓库" key="2">
            {userStaredRepos.map((item) => (
              <Repo repo={item} key={item.id} />
            ))}
          </Tabs.TabPane>
        </Tabs>
      </UserRepos>
    </UserRoot>
  );
}

// 由于如果不带token的话，github请求数据会被受限制，所以每次请求github的数据都要带上token
// 由于token是比较敏感的信息，不应该存储到客户端，导致发送请求的时候会被黑客拦截token
// 所以最好的方式是通过服务端代理
// axios.get('http://api.github.com/search/repositories?q=react')
// 所以改成请求自己的服务端接口
// axios.get("/github/search/repositories?q=react").then((res) => {
//   console.log(res);
// });
Index.getInitialProps = async ({ ctx, reduxStore }) => {
  // const result = await axios
  //   .get('/github/search/repositories?q=react')
  //   .then(resp => console.log(resp))

  const user = reduxStore.getState().user;
  if (!user || !user.id) {
    return {
      isLogin: false,
    };
  }

  if (!isServer) {
    if (cache.get("userRepos") && cache.get("userStaredRepos")) {
      return {
        userRepos: cache.get("userRepos"),
        userStaredRepos: cache.get("userStaredRepos"),
      };
    }

    // if (cachedUserRepos && cachedUserStaredRepos) {
    //   return {
    //     userRepos: cachedUserRepos,
    //     userStaredRepos: cachedUserStaredRepos,
    //   }
    // }
  }

  const userRepos = await request(
    {
      url: "/user/repos",
    },
    ctx.req,
    ctx.res
  );

  const userStaredRepos = await request(
    {
      url: "/user/starred",
    },
    ctx.req,
    ctx.res
  );

  return {
    isLogin: true,
    userRepos: userRepos.data,
    userStaredRepos: userStaredRepos.data,
  };
};

const LoginDiv = styled.div`
  height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
`;

const UserRoot = styled.div`
  display: flex;
  align-items: flex-start;
  padding: 20px 0;
`;
const UserInfo = styled.div`
  width: 200px;
  margin-right: 40px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
`;
const Login = styled.span`
  font-weight: 800;
  font-size: 20px;
  margin-top: 20px;
`;

const Name = styled.span`
  font-size: 16px;
  color: #777;
`;
const Bio = styled.span`
  margin-top: 20px;
  color: #333;
  font-weight: 500;
`;

const UserRepos = styled.div`
  flex-grow: 1;
`;

// connect 的第一个参数的返回值作为第二个组件的props，传入
// 第二个参数的组件通过props可以对state进行更改
// 把withRouter放在connect外面，才可以让他每次router变化时都强制更新
export default withRouter(
  connect(function mapState(state) {
    return {
      user: state.user,
    };
  })(Index)
);
